<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drag and Drop Example</title>
  <style>
    .container {
      display: flex;
      justify-content: space-around;
      margin-bottom: 20px;
    }

    .box {
      width: 100px;
      height: 100px;
      border: 2px solid #000;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
    }

    .item {
      width: 50px;
      height: 50px;
      background-color: #000;
      margin: 0 5px;
      cursor: move;
    }

    .item-container {
      display: flex;
      justify-content: center;
    }
  </style>
</head>

<body>
  <div class="container" id="boxContainer"></div>
  <div class="item-container" id="itemContainer"></div>

  <script>
    // 创建10个大盒子
    const boxContainer = document.getElementById('boxContainer');
    for (let i = 1; i <= 10; i++) {
      const box = document.createElement('div');
      box.className = 'box';
      box.textContent = i;
      box.id = `box-${i}`;
      box.addEventListener('dragover', dragOver);
      box.addEventListener('drop', drop);
      boxContainer.appendChild(box);
    }

    // 创建10个小方块
    const itemContainer = document.getElementById('itemContainer');
    for (let i = 1; i <= 10; i++) {
      const item = document.createElement('div');
      item.className = 'item';
      item.id = `item-${i}`;
      item.draggable = true;
      item.addEventListener('dragstart', dragStart);
      itemContainer.appendChild(item);
    }

    let draggedItem = null;

    function dragStart(e) {
      draggedItem = e.target;
      e.dataTransfer.setData('text/plain', e.target.id);
    }

    function dragOver(e) {
      e.preventDefault();
    }

    function drop(e) {
      e.preventDefault();
      const data = e.dataTransfer.getData('text');
      const draggedElement = document.getElementById(data);

      if (e.target.classList.contains('box')) {
        e.target.appendChild(draggedElement);
      } else if (e.target.classList.contains('item') && e.target.parentElement.classList.contains('box')) {
        e.target.parentElement.appendChild(draggedElement);
      }

      draggedItem = null;
    }

    // 允许从盒子中拖出
    document.addEventListener('dragover', (e) => {
      e.preventDefault();
    });

    document.addEventListener('drop', (e) => {
      if (e.target.id === 'itemContainer') {
        e.preventDefault();
        const data = e.dataTransfer.getData('text');
        const draggedElement = document.getElementById(data);
        e.target.appendChild(draggedElement);
      }
    });
  </script>
</body>

</html>